package com.ctyon.watchmanager.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.ctyon.common.event.UpdateCover;
import com.ctyon.common.util.DataUtil;
import com.ctyon.common.util.TSnackbarUtil;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.databinding.FragmentMineInfoBinding;
import com.ctyon.watchmanager.dialog.EditDialog;
import com.ctyon.watchmanager.dialog.EditPasswordDialog;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.ctyon.watchmanager.present.MineInfoPresenter;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.ctyon.watchmanager.util.OssUtil;
import com.orhanobut.logger.Logger;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.config.ISListConfig;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * CreateDate：19-6-25 on 上午9:14
 * Describe:
 * Coder: lee
 */
public class MineInfoFragment extends BaseFragment {

    public static final String TAG = "MineInfoFragment";

    private static final int REQUEST_LIST_CODE = 0;
    private static final int REQUEST_CAMERA_CODE = 1;

    private FragmentMineInfoBinding mBinding;
    private ISListConfig config;
    private EditPasswordDialog passwordDialog;
    private EditDialog nickDialog;

    public static MineInfoFragment newInstance() {
        final MineInfoFragment fragment = new MineInfoFragment();
        final Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_mine_info, container, false);
        mBinding.setMineInfoPresenter(mineInfoPresenter);

        return mBinding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mBinding.setManager(BasicApp.getInstance().getManager());
    }

    @Override
    public void onResume() {
        super.onResume();
        mBinding.setCover(BasicApp.getInstance().getManager().getImg());
    }

    private final MineInfoPresenter mineInfoPresenter = new MineInfoPresenter() {

        @Override
        public void onEditNick() {
            Logger.t(LTAG).i("onEditNick");
            showNickDialog();
        }

        @Override
        public void onChangeCover() {
            Logger.t(LTAG).i("onChangeCover");
            single();
        }

        @Override
        public void onPasswordClick() {
            Logger.t(LTAG).i("onPasswordClick");
            showPasswordDialog();
        }

    };

    private void single() {
        if (null == config) {
            config = new ISListConfig.Builder()
                    // 是否多选
                    .multiSelect(false)
                    .btnText("Confirm")
                    // 确定按钮背景色
                    //.btnBgColor(Color.parseColor(""))
                    // 确定按钮文字颜色
                    .btnTextColor(Color.WHITE)
                    // 使用沉浸式状态栏
                    .statusBarColor(Color.parseColor("#FFFFFF"))
                    // 返回图标ResId
                    .backResId(R.mipmap.ic_back)
                    .title("选择照片")
                    .titleColor(Color.BLACK)
                    .titleBgColor(Color.parseColor("#FFFFFF"))
                    .allImagesText("全部照片")
                    .needCrop(true)
                    .cropSize(1, 1, 200, 200)
                    // 第一个是否显示相机
                    .needCamera(true)
                    // 最大选择图片数量
                    .maxNum(9)
                    .build();
        }

        ISNav.getInstance().toListActivity(this, config, REQUEST_LIST_CODE);
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onUpdateCover(UpdateCover updateCover) {
        Logger.t(LTAG).i("Event : onUpdateCover");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_LIST_CODE && resultCode == getActivity().RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra("result");
            for (String path : pathList) {
                Logger.t(LTAG).i("file : " + path);

                BasicApp.getInstance().getAppExecutors().networkIO().execute(() -> OssUtil.getOssInstance().uploadPicture(path));

                BasicApp.getInstance().getManager().setImg(path);
                mBinding.setManager(BasicApp.getInstance().getManager());

            }
        } else if (requestCode == REQUEST_CAMERA_CODE && resultCode == getActivity().RESULT_OK && data != null) {
            String path = data.getStringExtra("result");
            Logger.t(LTAG).i("camera : " + path);
        }
    }

    private final EditPasswordDialog.PasswordDialogCallback editPasswordDialogCallback = (po, pn) -> {
        Logger.t(LTAG).i("po = " + po + "  pn = " + pn);
        final String method = "updatePassword";
        if (NetService.getInstance().isDisable(method)){
            TSnackbarUtil.TSBError(getActivity(), "请稍候...");
            return;
        }
        NetService.getInstance()
                .method(method)
                .updatePassword(BasicApp.getInstance().getManager().getManagerId(), po, pn)
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponseEntity>() {
                    @Override
                    public void onSuccess(BaseResponseEntity responseEntity) {
                        Logger.d("onSuccess : " + responseEntity.toString());
                        TSnackbarUtil.TSBSuccess(getActivity(), "修改成功");
                        BasicApp.getInstance().getManager().setPassword(pn);
                    }

                    @Override
                    public String onOver() {
                        return method;
                    }
                });

    };

    private final EditDialog.EditDialogCallback editDialogCallback = (nick) -> {
        Logger.t(LTAG).i("nick : " + nick);
        if (DataUtil.isEmptyOr(nick)){
            TSnackbarUtil.TSBError(getActivity(), "请输入合法昵称");
            return;
        }
        if (nick.length() > 10){
            TSnackbarUtil.TSBError(getActivity(), "昵称最多10个字");
            return;
        }
        final String method = "updateNick";
        if (NetService.getInstance().isDisable(method)){
            TSnackbarUtil.TSBError(getActivity(), "请稍候...");
            return;
        }
        NetService.getInstance()
                .method(method)
                .updateNick(BasicApp.getInstance().getManager().getManagerId(), nick)
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponseEntity>() {
                    @Override
                    public void onSuccess(BaseResponseEntity responseEntity) {
                        Logger.d("onSuccess : " + responseEntity.toString());
                        TSnackbarUtil.TSBSuccess(getActivity(), "修改成功");
                        BasicApp.getInstance().getManager().setNickName(nick);
                    }

                    @Override
                    public String onOver() {
                        return method;
                    }
                });
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void showPasswordDialog() {
        if (null == passwordDialog) {
            Logger.t(LTAG).i("Create Dialog");
            passwordDialog = new EditPasswordDialog(getActivity(), R.style.CustomDialog);
            passwordDialog.setEditCallback(editPasswordDialogCallback);
            passwordDialog.setCancelable(false);
            Window window = passwordDialog.getWindow();
            window.setGravity(Gravity.CENTER);
            window.setWindowAnimations(R.style.CustomDialogStyle);
        }
        passwordDialog.show();
    }

    private void showNickDialog() {
        if (null == nickDialog) {
            Logger.t(LTAG).i("Create Dialog");
            nickDialog = new EditDialog(getActivity(), R.style.CustomDialog);
            nickDialog.setEditCallback(editDialogCallback);
            nickDialog.setCancelable(false);
            nickDialog.setTitle("修改昵称");
            nickDialog.setText(BasicApp.getInstance().getManager().getNickName());
            nickDialog.setHint("输入昵称");
            Window window = nickDialog.getWindow();
            window.setGravity(Gravity.CENTER);
            window.setWindowAnimations(R.style.CustomDialogStyle);
        }
        nickDialog.show();
    }

}
